//
//  YTTMessageController.m
//  跑圈儿
//
//  Created by 唐康 on 16/4/19.
//  Copyright © 2016年 唐康. All rights reserved.
//

#import "YTTWeatherController.h"

#import <RESideMenu.h>
#import <MJRefresh.h>
#import <CoreLocation/CoreLocation.h>
#import "YTTDataTool.h"
#import "YTTHeaderView.h"
#import "YTTNetWorTool.h"
#import "YTTLocationTool.h"
#import "YTTDetail.h"
#import <GDataXMLNode.h>
#import <UIImageView+WebCache.h>
#import "YTTHourly.h"
#import "YTTCityGroupViewController.h"



@interface YTTWeatherController ()<UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate>


{
    
    NSString *currentElement;

    NSString *currenValue;
    
    NSMutableDictionary *rootDic;
    
    NSMutableArray *finalArray;
    
}

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)CLLocation *userLocaton;
@property(nonatomic, strong)NSArray *dailArray;
@property(nonatomic, strong)NSArray *hourlyArray;
@property(nonatomic, strong)YTTHeaderView *hearderView;
@property(nonatomic, strong)YTTNow *nowData;

//动画相关

@property(nonatomic, strong)UIImageView *birdImage;
@property(nonatomic, strong)UIImageView *birdRefImage;
@property(nonatomic, strong)UIImageView *backGroundView;
@property(nonatomic, strong)UIImageView *sunImage;
@property(nonatomic, strong)UIImageView *cloudImageViewF;
@property(nonatomic, strong)UIImageView *cloudImageViewS;
@property(nonatomic, strong)UIImageView *cloudImageViewT;
@property(nonatomic, strong)UIImageView *cloudImageViewFourth;



@end

@implementation YTTWeatherController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;
    
    //验证城市组是否可以转换
    //    NSArray *array = [TyDataManager getAllCityGroups];
    
    //创建背景视图
    [self createBackgroundView];
    //创建tableView
    [self creatTableView];
    //创建头部视图
    [self createHeaderView];
    //创建下拉刷新控件
    [self createRefreshControl];
    //获取用户的位置并发送请求
    [self getLocationAndSendRequest];
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shouldChangeCity:) name:@"DidChangeCity" object:nil];
    //添加动画
#warning TODO:动画定时需要修修正
    //    [self addTimer];

    
    
    
    
   // [self setupNavigationitem];
}
- (void)setupNavigationitem{
    self.navigationItem.title = @"天气";
    UIBarButtonItem  *friendList = [UIBarButtonItem itemWithImage:@"friend" highLightImage:@"friend_click" target:self action:@selector(gotoFriendlist)];
    self.navigationItem.rightBarButtonItems = @[friendList];
}

- (void)gotoFriendlist{
    
    
    
    
}

-(void)addTimer{
    
    NSTimer *timer1 = [NSTimer timerWithTimeInterval:13 target:self.birdImage selector:@selector(birdFlyAnimationWithToValue:duration:) userInfo:nil repeats:YES];
    [timer1 fire];
    
    [[NSRunLoop mainRunLoop]addTimer:timer1 forMode:NSDefaultRunLoopMode];
    
    NSTimer *timer2 = [NSTimer timerWithTimeInterval:13 target:self.birdRefImage selector:@selector(birdFlyAnimationWithToValue:duration:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:timer2 forMode:NSDefaultRunLoopMode];
    [timer2 fire];
    NSTimer *timer3 = [NSTimer timerWithTimeInterval:71 target:self.cloudImageViewF selector:@selector(birdFlyAnimationWithToValue:duration:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:timer3 forMode:NSDefaultRunLoopMode];
    [timer3 fire];
    NSTimer *timer4 = [NSTimer timerWithTimeInterval:71 target:self.cloudImageViewS selector:@selector(birdFlyAnimationWithToValue:duration:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:timer4 forMode:NSDefaultRunLoopMode];
    [timer4 fire];

    
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addAnimation];
}


//动画移动方法
- (CABasicAnimation *)birdFlyAnimationWithToValue:(NSNumber *)toValue duration:(NSInteger)duration
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    animation.toValue = toValue;
    animation.duration = duration;
    animation.removedOnCompletion = NO;
    animation.repeatCount = 1;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}

//添加动画图片

-(void)addAnimation
{
    
    //鸟
    NSMutableArray *allImage = [NSMutableArray array];
    for (int i = 1; i < 9; i++) {
        NSString *fileName = [NSString stringWithFormat:@"ele_sunnyBird%d.png",i];
        NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        [allImage addObject:image];
    }
    //鸟 本体
    self.birdImage = [[UIImageView alloc]initWithFrame:CGRectMake(-30, YTTScreenH * 0.2, 70, 50)];
    [self.backGroundView addSubview:self.birdImage];
    [self.birdImage setAnimationImages:allImage];
    self.birdImage.animationRepeatCount = MAXFLOAT;
    self.birdImage.animationDuration = 1;
    [self.birdImage startAnimating];
    //鸟 倒影
    self.birdRefImage = [[UIImageView alloc]initWithFrame:CGRectMake(-30, YTTScreenH * 0.8, 70, 50)];
    [self.backGroundView addSubview:self.birdRefImage];
    [self.birdRefImage setAnimationImages:allImage];
    self.birdRefImage.animationRepeatCount = MAXFLOAT;
    self.birdRefImage.animationDuration = 1;
    self.birdRefImage.alpha = 0.6;
    [self.birdRefImage startAnimating];
    
    //添加动画效果
    [self.birdImage.layer addAnimation:[self birdFlyAnimationWithToValue:@(YTTScreenW + 30) duration:15] forKey:nil];
    [self.birdRefImage.layer addAnimation:[self birdFlyAnimationWithToValue:@(YTTScreenW + 30) duration:15] forKey:nil];
   
    
    //云朵效果
    self.cloudImageViewF = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud2"]];
    CGRect frame = self.cloudImageViewF.frame;
    frame.size = CGSizeMake(YTTScreenH * 0.7, YTTScreenW * 0.5);
    self.cloudImageViewF.frame = frame;
    self.cloudImageViewF.center = CGPointMake(YTTScreenH * 0.25, YTTScreenH * 0.7);
    [self.cloudImageViewF.layer addAnimation:[self birdFlyAnimationWithToValue:@(YTTScreenW + 30) duration:70] forKey:nil];
    
    
    //云朵倒影
    self.cloudImageViewS = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud1"]];
    self.cloudImageViewS.frame = frame;
    self.cloudImageViewS.center = CGPointMake(YTTScreenW * 0.05, YTTScreenH * 0.7);
    [self.cloudImageViewS.layer addAnimation:[self birdFlyAnimationWithToValue:@(YTTScreenW + 30) duration:70] forKey:nil];
    //    self.cloudImageViewT = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud1"]];
    //    self.cloudImageViewFourth = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ele_sunnyCloud1"]];
    //
    [self.view addSubview:self.cloudImageViewF];
    [self.view addSubview:self.cloudImageViewS];
    
    
    
}

//创建下拉刷新控件
- (void)createRefreshControl
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getLocationAndSendRequest)];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    //马上刷新
    [header beginRefreshing];
    //设置header
    self.tableView.mj_header = header;
    
}

//通知中心的方法
- (void)shouldChangeCity:(NSNotification *)notification
{
    //获取传过来的参数
    NSString *cityName = notification.userInfo[@"cityName"];
    NSLog(@"城市名字:%@",cityName);
    [self sendRequestToServer:cityName];
    //    [self updateHearderView:cityName];
}


//创建头部视图
- (void)createHeaderView
{
    
    self.hearderView = [[YTTHeaderView alloc] initWithFrame:YTTBOUNDS];
    [self.hearderView.menuButton addTarget:self action:@selector(clickMenuButton) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.tableView.tableHeaderView = self.hearderView;
}


//创建背景视图
- (void)createBackgroundView
{
    
    self.backGroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sunny"]];
    self.backGroundView.frame = YTTBOUNDS;
    [self.view addSubview:self.backGroundView];
}

//创建talbeView
- (void)creatTableView

{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, YTTScreenW, YTTScreenH - 64) style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
  //  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    
}

//更新界面
- (void)updateHearderView:(NSString *)cityName
{
    self.hearderView.cityLabel.text = cityName;
    if (self.nowData.iconCodeUrl && self.nowData.tmp && self.dailArray[0]) {
        self.hearderView.temperatureLabel.text = self.nowData.tmp;
        YTTDetail *daily = self.dailArray[0];
        self.hearderView.hiloLabel.text = [NSString stringWithFormat:@"%@/%@",daily.min,daily.max];
        self.hearderView.conditionsLabel.text = self.nowData.qlty;
        [self.hearderView.iconView sd_setImageWithURL:[NSURL URLWithString:self.nowData.iconCodeUrl] placeholderImage:[UIImage imageNamed:@"999"]];
    }
    
    
}

//请求相关
- (void)getLocationAndSendRequest
{
    [YTTLocationTool getUserLocation:^(double lat, double lon, NSString *cityName) {
        CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
        self.userLocaton = location;
        //定位后查询
        //查询后更新界面
        [self sendRequestToServer:cityName];
        [self updateHearderView:cityName];
        
    }];
    
}

//发送请求数据
- (void)sendRequestToServer:(NSString *)cityName
{
    
    NSString *baseUrl = @"https://api.heweather.com/x3/weather";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"city"] = cityName;
    params[@"key"] = @"025261843a564e1f9d1d60f37d2d2242";
    [YTTNetWorTool sendGetRequestWithUrl:baseUrl parameters:params success:^(id responseObject) {
        self.dailArray = [YTTDataTool getAllDailData:responseObject];
        self.hourlyArray = [YTTDataTool getAllHourlyData:responseObject];
        self.nowData = [YTTDataTool getNowData:responseObject];
        
        //刷新
        [self.tableView reloadData];
        [self updateHearderView:cityName];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        
         [self.tableView.mj_header endRefreshing];
    }];
    
    
    
    
} 
#pragma mark - 按钮触发方法
- (void)clickMenuButton {

    //创建城市视图控制器对象(navController)
    
    YTTCityGroupViewController *cityVC = [[YTTCityGroupViewController alloc] init];

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:cityVC];
    //显示
    [self presentViewController:navController animated:YES completion:nil];
    
    
    
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ? self.hourlyArray.count + 1 : self.dailArray.count + 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    
    
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor =[UIColor whiteColor];
    //设置cell不可点中
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text =  @"Hourly Forecast Info.";
            cell.detailTextLabel.text = nil;
            cell.imageView.image = nil;
        } else {
            
            //显示时间段的天气
            YTTHourly *hourly = self.hourlyArray[indexPath.row - 1];
            cell.imageView.image = nil;
            cell.textLabel.text = hourly.time;
            cell.detailTextLabel.text = hourly.tmp;
           
            
        }
    } else {
        
        
        if (indexPath.row == 0) {
            
            cell.textLabel.text = @"Daily Forecast Info.";
            cell.detailTextLabel.text = nil;
            cell.imageView.image = nil;
        } else {
            //显示未来几天的天气
            YTTDetail *daily = self.dailArray[indexPath.row - 1];
            cell.textLabel.text = daily.data;
           cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ / %@", daily.max, daily.min];
           
            
            
            
            //下载图片 显示天气对应的图片
         [cell.imageView sd_setImageWithURL:[NSURL URLWithString:daily.iconUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        }
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //获取每个section的行数
    NSInteger rowCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
    return YTTScreenH / rowCount;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
